package com.nxj.factory;

import java.util.HashMap;
import java.util.Map;

@Deprecated
public class IOCFactory {

    private final static Map<String, Object> map = new HashMap<>();

    // 初始化阶段解析 beans_bak.xml 文件 将所有配置的 bean 加载到内存中 map
    /*
    static {
        System.out.println("开始加载 beans.xml");
        InputStream resourceAsStream = IOCFactory.class.getClassLoader().getResourceAsStream("beans.xml");
        SAXReader saxReader = new SAXReader();
        try {
            Document document = saxReader.read(resourceAsStream);
            Element root = document.getRootElement();
            ((List<Element>) root.selectNodes("//bean")).forEach((Consumer) o -> {
                try {
                    String id = ((Element) o).attributeValue("id");
                    String klass = ((Element) o).attributeValue("class");
                    System.out.println("id: " + id + ", klass: " + klass);
                    map.put(id, Class.forName(klass).newInstance());
                } catch (Exception e1) {
                    e1.printStackTrace();
                }
            });

            root.selectNodes("//property").forEach(new Consumer() {
                @Override
                public void accept(Object o) {
                    Object parentBean = map.get(((Element) o).getParent().attributeValue("id"));
                    System.out.println(parentBean);
                    for (Method method : parentBean.getClass().getMethods()) {
                        if (method.getName().equals("set" + ((Element) o).attributeValue("name"))) {
                            try {
                                method.invoke(parentBean, map.get(((Element) o).attributeValue("ref")));
                            } catch (IllegalAccessException e) {
                                e.printStackTrace();
                            } catch (InvocationTargetException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }*/

    public static Object getBean(String beanId) {
        System.out.println("beanId: " + beanId);
        System.out.println(map.get(beanId));
        return map.get(beanId);
    }
}
